<template>
  <div class="my-edit">
    <ZJHeader title="修改信息"/>
    <van-form class="edit-form" @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            readonly
            label="用户名"
            name="username"
            autocomplete="off"
            placeholder="用户名"
            v-model="formModel.username"
        />
        <van-field
            label="用户昵称"
            name="nickName"
            autocomplete="off"
            placeholder="用户昵称"
            v-model="formModel.nickName"
        />
        <van-field
            autocomplete="off"
            type="email"
            name="email"
            label="邮箱"
            placeholder="邮箱"
            v-model="formModel.email"
            :rules="[{ required: true, message: '请填写邮箱' }]"
        />
        <van-field
            name="sign"
            label="个性签名"
            autocomplete="off"
            placeholder="个性签名"
            v-model="formModel.sign"
        />
        <van-field
            is-link
            readonly
            label="性别"
            name="gender"
            autocomplete="off"
            placeholder="点击选择性别"
            v-model="formModel.gender"
            @click="showPicker = true"
        />
        <van-popup v-model:show="showPicker" position="bottom">
          <van-picker
              :columns="genderOptions"
              @confirm="genderConfirm"
              @cancel="showPicker = false"
          />
        </van-popup>
        <van-field name="photo" label="头像上传">
          <template #input>
            <van-uploader :max-count="1" v-model="avatarList"
                          :after-read="afterPhotoUpload"/>
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 20px;">
        <van-button round block type="primary" native-type="submit">
          保存
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import {onActivated, ref} from "vue";
import {Toast, UploaderFileListItem} from "vant";

import {ISubmitParams, IUserInfo, ZJFileListItem} from "@/views/ZJMy/MyEdit/types";
import ZJHeader from "@/components/ZJHeader/ZJHeader.vue";
import useMyModule from "@/store/myModule";
import router from "@/router";
import useGlobalModule from "@/store/globalModule";

const myModule = useMyModule()
const globalModule = useGlobalModule()
// 头像处理
let needTimestamp = false
const formData = new FormData()
const avatarList: any = ref([])
let timestamp = new Date().getTime().toString() // 每次进入修改页面这个都不一样
const afterPhotoUpload = async (file: ZJFileListItem) => {
  file.status = "uploading"
  file.message = "上传中..."
  formData.append("file", file.file as File)
  formData.append("fileId", timestamp)
  let data = await globalModule.uploadFileAction(formData, timestamp)
  if (data) {
    file.status = "done"
    file.message = "上传成功"
    file.url = data.photoUrl
    needTimestamp = true
  } else {
    file.status = "failed"
    file.message = "上传失败"
  }
}

// 获取最新的用户信息和重置上传图片的时间
const userInfo = ref<IUserInfo>()
onActivated(async () => {
  timestamp = new Date().getTime().toString()
  const data = await myModule.getMyAction("/my/edit")
  if (data) {
    userInfo.value = data
    formModel.value.username = userInfo.value.username
    formModel.value.nickName = userInfo.value.nickName
    formModel.value.email = userInfo.value.email
    formModel.value.sign = userInfo.value.sign ?? ""
    formModel.value.gender = genderOptions[userInfo.value.gender]
    avatarList.value = [{
      url: userInfo.value?.photo
    }]
  }
})
// 表单处理
const formModel = ref<ISubmitParams>({
  username: "",
  nickName: "",
  email: "",
  sign: "",
  gender: "未知",
  photo: ""
})
const onSubmit = async (myNewInfo: ISubmitParams) => {
  if (userInfo.value) {
    myNewInfo.gender = genderOptions.indexOf(myNewInfo.gender as string)
    if (needTimestamp) { // 如果需要上传图片
      myNewInfo.photo = timestamp
    } else { // 不需要的话因为myNewInfo有被赋值所以会被拿过来，事实上不需要
      delete myNewInfo.photo
    }
    delete myNewInfo.username
    const flag = await myModule.updateMyAction(myNewInfo)
    if (flag) {
      Toast.success("修改成功")
      await router.replace("/my")
    }
  }
};
// 选择器处理
const genderOptions = ["女", "男", "未知"]
const showPicker = ref(false)
const genderConfirm = (currentGender: string) => {
  formModel.value.gender = currentGender
  showPicker.value = false
}
</script>

<style scoped lang="less">
@import "src/assets/css/variable";
@import "src/assets/css/mixins";

.my-edit {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 888;
  background-color: @theme-grey-color;

  .edit-form {
    .van-cell-group {
      margin: 0;
    }
  }
}
</style>
